//
//  OrderListProxy.m
//  ios-supplier
//
//  Created by feynmanyuan on 15/4/15.
//  Copyright (c) 2015年 feynmanyuan. All rights reserved.
//

#import "OrderListProxy.h"
#import "OrderListCell.h"
#import "DeliveriesCell.h"
#import "JFBOrderDS.h"
#import "JFBCompleteOrderDS.h"
#import "UIAlertView+AFNetworking.h"
#import "UIRefreshControl+AFNetworking.h"
#import "SVPullToRefresh.h"
#import "JFBLoadingAnimation.h"

@implementation OrderListProxy

- (id)initWithFrame:(CGRect)frame orderType:(NSString * )orderType {
    self = [super initWithFrame:frame];
    if (self) {
        _cellFrame = [[NSMutableDictionary alloc] init];
        
        UIView *tableHeadrView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.bounds.size.width, 10)];
        [tableHeadrView setBackgroundColor:PanelBgColorDefault];
        
        UITableView * tableView = [[UITableView alloc] initWithFrame:self.bounds style:UITableViewStylePlain];
        tableView.tableHeaderView = tableHeadrView;
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        tableView.backgroundColor = UIColorFromRGB(PanelBgColor);

        [self addSubview:tableView];
        
        self.items = [@[] mutableCopy];
        self.orderType = orderType;
        
        self.tableView = tableView;
        self.tableView.dataSource = self;
        self.tableView.delegate = self;
        [self.tableView setSeparatorStyle: UITableViewCellSeparatorStyleNone];
        
        [self tableRefreshExt];
        
        self.pager = [[JFBPager alloc] init];
        
        [self reload:nil];
    }
    return self;
}
- (id)initWithFrame:(CGRect)frame orderType:(NSString * )orderType date: (NSString *)date;
{
    _dateInfo = date;
    return [self initWithFrame: frame orderType: orderType];
}

-(void)tableRefreshExt {
    [self.tableView addLegendHeaderWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    self.tableView.header.updatedTimeHidden = YES;
}

-(void)loadNewData {
    [JFBOrderDS loadOrderList:^(NSArray *orders, NSError *error) {
        [self.tableView.header endRefreshing];
        self.items = [@[] mutableCopy];
        if (error || orders.count == 0) {
            [ComponentsUtils emptyStringTips:self.tableView tips:@"当前没有订单，继续努力哦～"];
        } else {
            if( self.items.count == 0 ) {
                [ComponentsUtils cleanEmptyTips:self.tableView];
            }
            _cellFrame = [[NSMutableDictionary alloc] init];
            [self.items addObjectsFromArray:orders];
        }
        [self.tableView reloadData];
    } orderType:[self.orderType isEqual:@"undealer"] ? kOrderStatusUndealer : kOrderStatusDeliveries pager:self.pager];
}

- (void)reload:(__unused id)sender {
    JFBLoadingAnimation * animation = [[JFBLoadingAnimation alloc] init:self.tableView];
        [JFBOrderDS loadOrderList:^(NSArray *orders, NSError *error) {
            [animation stop];
            self.items = [@[] mutableCopy];
            if (error || orders.count == 0) {
                [ComponentsUtils emptyStringTips:self.tableView tips:@"当前没有订单，继续努力哦～"];
            } else {
                if( self.items.count == 0 ) {
                    [ComponentsUtils cleanEmptyTips:self.tableView];
                }
                // 由于API数据都没有分页支持，所以应清空之前的数据重新渲染
                _cellFrame = [[NSMutableDictionary alloc] init];
                [self.items addObjectsFromArray:orders];
            }
            [self.tableView reloadData];
        } orderType:[self.orderType isEqual:@"undealer"] ? kOrderStatusUndealer : kOrderStatusDeliveries pager:self.pager];
}

- (void)insertRowAtTop {
    __weak OrderListProxy *weakSelf = self;
    JFBPager *pager = [[JFBPager alloc]init];
    [JFBOrderDS loadOrderList:^(NSArray *orders, NSError *error) {
        [weakSelf.tableView beginUpdates];
        [weakSelf.tableView endUpdates];
        [weakSelf.tableView.pullToRefreshView stopAnimating];
        [self.tableView reloadData];
    } orderType:[self.orderType isEqual:@"undealer"] ? kOrderStatusUndealer : kOrderStatusDeliveries pager:pager];
  
    NSLog(@"insertRowAtTop");
}

- (void)insertRowAtBottom {
    __weak OrderListProxy *weakSelf = self;
    JFBPager *pager = [[JFBPager alloc]init];

    [JFBOrderDS loadOrderList:^(NSArray *orders, NSError *error) {
        [weakSelf.tableView beginUpdates];
        [weakSelf.tableView endUpdates];
        [weakSelf.tableView.infiniteScrollingView stopAnimating];
    } orderType:kOrderStatusUndealer pager:pager];
    
    [self.tableView reloadData];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.items.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *key = [NSString stringWithFormat:@"%ld", (long)indexPath.row];
    NSNumber *height = [_cellFrame objectForKey:key];
    if( height ) {
        return [height integerValue];
    } else {
        OrderCellBase *cell = (OrderCellBase*)[self tableView:self.tableView cellForRowAtIndexPath:indexPath];
        CGFloat cellHeight = cell.height;
        [_cellFrame setObject:[NSNumber numberWithFloat:cellHeight] forKey:key];
        cell.order = self.items[indexPath.row];
        return cellHeight;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    OrderCellBase *cell;
    static NSString *cellIdentifier = @"OrderListCellIdentifier";
    cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if(!cell){
        if([self.orderType isEqualToString:@"undealer"]) {
            cell= [[OrderListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier frame:self.tableView.bounds];
        } else if( [self.orderType isEqualToString:@"deliveries"] ) {
            cell= [[DeliveriesCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier frame:self.tableView.bounds];
        }
    }
    cell.order = self.items[indexPath.row];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}



#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    JFBOrderDS *ds = self.items[indexPath.row];
    if (self.dateInfo) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"selectDayOrderItem" object:self userInfo:[NSDictionary dictionaryWithObjects:@[self.orderType, ds, self] forKeys:@[@"orderType", @"order", @"refreshDelegate"]]];
        return;
    }
    [[NSNotificationCenter defaultCenter] postNotificationName:@"selectOrderItem" object:self userInfo:[NSDictionary dictionaryWithObjects:@[self.orderType, ds, self] forKeys:@[@"orderType", @"order", @"refreshDelegate"]]];
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

-(void)reload {
    [self.tableView.header beginRefreshing];
}

#pragma mark - Recommend cell delegate
@end
